import { getTeacherList } from '@/api/teacher_home'
import { getShowProfessions } from '@/api/common_apis'

export default {
  namespaced: true,
  state: ()=>({
    teacher_list: [],
    professions: [],
    teacherPager: {
      page: 1,
      limit: 8,
      total: 0
    },
    profession_id: '0',
  }),
  mutations: {
    setTeacherList(state, { list, total }) {
      state.teacher_list = list
      state.teacherPager.total = total
    },
    setProfessionList(state, data) {
      data.unshift({ path: 'all', profession_id: '0', profession_name: '全部' })
      state.professions = data
    },
    setProfessionId(state, data) {
      state.profession_id = data
    },
    setPage(state,data){
      state.teacherPager.page = data
    }
  },
  actions: {
    async init({ commit, dispatch, rootState, state }, params) {
      await dispatch('fetchProfessionList')
      let currentProfession = state.professions.filter(item => item.path === params.profession_path && item)
      let profession_id = currentProfession.length ? currentProfession[0].profession_id : '0'
      commit('setProfessionId', profession_id)
      commit('setPage', params.page)
      let { page, limit } = state.teacherPager
      await dispatch('dispatchTeacherList', { page, profession_id, limit })
    },
    async dispatchTeacherList({ commit }, params) {
      let res = {}
      try {
        let { data: { data = [], total = 0 } } = await getTeacherList(params)
        res.list = data
        res.total = +total
      } catch (err) {
        res = { list: [], total: 0 }
      }
      commit('setTeacherList', res)
    },
    // 获取专业以及对应的科目
    async fetchProfessionList({ store, commit }, params = {}) {
      let res = await getShowProfessions(params).catch(err => {
        return { data: [] }
      })
      res.data && Array.isArray(res.data) && commit('setProfessionList', res.data)
      return true
    },
  },
  getters: {}
}